<template>

    <div class="code-select">
      <el-row style="line-height: 46px; min-height: 46px;">
        <el-col :span="12" style="padding: 0 10px;">
          <el-input class="tree-input" v-model="filterText" placeholder="请输入过滤条件" :suffix-icon="Search" />
        </el-col>
        <el-col :span="12">
          <p>已选：{{selectedData.length}}</p>
          <p class="clear" @click="handleClear">清空</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-tabs type="border-card" >
            <div v-for="(item,index) in props.range" :key="index">
              <el-tab-pane label="本部门" v-if="item==='dept'">
              <el-tree
                node-key="id"
                v-if="treeVisible"
                :load="loadNode"
                lazy
                show-checkbox
                :props="defaultProps"
                ref="treeRef"
                @check-change="handleCheckClick"
                :filter-node-method="filterNode"
                :default-checked-keys="defaultCheckKeys"
              />
            </el-tab-pane>
              <el-tab-pane label="本单位" v-if="item==='unit'">
              <el-tree
                :key="unitTreeKey"
                node-key="id"
                :data="unitTreeData"
                v-if="treeVisible"
                :load="loadNode"
                :lazy="isLazy"
                show-checkbox
                :auto-expand-parent="true"
                :props="defaultProps"
                ref="treeRef"
                @check-change="handleCheckClick"
                :filter-node-method="filterNode"
                :default-expand-all="isExpandAll"
                :default-expanded-keys="defaultExpandedKeys"
                :default-checked-keys="defaultCheckKeys"
                @node-click="handleNodeClick"
              />
            </el-tab-pane>

            </div>
          </el-tabs>

        </el-col>
        <el-col :span="12">
          <ul>
            <li v-for="(item,index) in selectedData" :key="item.id">
              <p>{{item.label}}</p>
              <el-icon style="float: right;cursor:pointer;" color="#409EFC" @click="cancelNode(index,item)">
                <Close/>
              </el-icon>
            </li>
          </ul>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" @click="handleButton">确定</el-button>
          <el-button type="primary" @click="handleClose">关闭</el-button>
        </el-col>
      </el-row>
    </div>

  </template>

<script setup lang="ts">
import { ElTree, ElMessage } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ref, watch, onMounted, nextTick } from 'vue'
import { Search, Close } from '@element-plus/icons-vue'
import { loadAllUserTree } from '@/api/system/user/UserManager'
import { fa } from 'element-plus/es/locale'

const emit = defineEmits(['close-dialog', 'commit-selected'])
const treeRef = ref()
const treeVisible = ref(true)
const filterText = ref('')
const selectedData = ref([])
const defaultExpandedKeys = ref([])
const defaultCheckKeys = ref([])
const isLazy = ref(true)
const isExpandAll = ref(false)
const unitTreeData = ref([])
const unitTreeKey = ref()
const props = defineProps({
  // 已选
  selected: {
    type: Array,
    default: () => []
  },
  // 数据显示范围
  range: {
    type: Array,
    default: () => ['unit']
  },
  // 可选标签
  tags: {
    type: Array,
    default: () => ['user']
  }
})

const filterNode = (value:any, data:any) => {
  if (!value) return true
  return data.label.includes(value)
}

watch(filterText, (val) => {
  if (!val) {
    treeVisible.value = false
    nextTick(() => {
      treeVisible.value = true
    })
    isExpandAll.value = false
    isLazy.value = true
  } else {
    loadAllUserTree({ fid: '', search: val }).then((data) => {
      unitTreeData.value = data.data
    })
    isExpandAll.value = true
    isLazy.value = false
  }
  unitTreeKey.value = +new Date()
})

const handleNodeClick = (nodes, node, self) => {
  console.log(nodes)
}

const defaultProps = {
  children: 'children',
  label: 'label',
  // disabled: 'disabled',
  isLeaf: 'leaf',
  id: 'id'
}

onMounted(() => {
  props.selected.forEach((value, index) => {
    selectedData.value.push({ id: value.targetId, value: value.targetId, label: value.targetName })
    defaultExpandedKeys.value.push(value.targetId)
    defaultCheckKeys.value.push(value.targetId)
  })
})

interface Tree {
  label: string
  leaf?: boolean
}

const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
  const fid = node.data.value
  setTimeout(() => {
    loadAllUserTree({ fid: fid, search: '', tags: props.tags }).then((data) => {
      resolve(data.data)
    })
  }, 500)
}

const handleClear = () => {
  selectedData.value.forEach((item, index) => {
    props.range.forEach((rangeItem, rangeIndex) => {
      treeRef.value[rangeIndex].setChecked(item.value, false)
    })
    // treeRef.value[0].setChecked(item.value, false)
  })
  nextTick(() => {
    defaultCheckKeys.value = []
    selectedData.value = []
  })
}

const handleCheckClick = (node) => {
  if (node.isLeaf) {
    if (defaultCheckKeys.value.includes(node.id)) {
      selectedData.value = selectedData.value.filter(function (item, index) {
        return item.id !== node.id
      })
      defaultCheckKeys.value.splice(defaultCheckKeys.value.indexOf(node.id), 1)
    } else {
      selectedData.value.push(node)
      defaultCheckKeys.value.push(node.id)
    }
  }
}

const cancelNode = (index, node) => {
  console.log(node)
  if (defaultCheckKeys.value.includes(node.id)) {
    props.range.forEach((item, index) => {
      treeRef.value[index].setChecked(node.id, false, false)
    })
    // treeRef.value[0].setChecked(node.id, false, false)
  }
}

const handleButton = () => {
  if (selectedData.value.length > 0) {
    emit('commit-selected', selectedData.value)
  } else {
    ElMessage.error('请选择数据')
  }
}

const handleClose = () => {
  emit('close-dialog')
}

</script>
<style lang="scss">

  .el-dialog__body{
    padding: 10px 20px;
  }

  .code-select{
    width: 100%;

    .el-tree,ul {
      height: 360px;
      overflow-y: auto;
    }

    .el-col{
      border: 1px solid #f3f2f2;
    }

    p{
      display: inline-block;
      padding: 3px 10px;
      margin: 0;
    }

    .clear{
      float: right;
      color: #1a66b1;
      cursor:pointer;
    }

    li{
        padding: 3px;
      }

    li p {
      padding: 0;
      width: calc(100% - 100px);
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    .el-button{
      margin: 5px;
    }
  }

  </style>
